package cn.mengfly.testnrz.im.server;

import cn.mengfly.testnrz.im.client.bean.User;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class SessionMap {
    private SessionMap() {
    }

    private final static SessionMap instance = new SessionMap();

    private ConcurrentHashMap<String, ServerSession> map = new ConcurrentHashMap<>();

    public static SessionMap inst() {
        return instance;
    }

    public void addSession(ServerSession s) {
        map.put(s.getSessionId(), s);
        System.out.println("用户登录:id= " + s.getUser().getUid() + "  在线总数：" + map.size());
    }

    public ServerSession getSession(String sessionId) {
        return map.getOrDefault(sessionId, null);
    }

    public List<ServerSession> getSessionBy(String userId) {
        return map.values().stream().filter(s -> s.getUser().getUid().equals(userId)).collect(Collectors.toList());
    }

    public void removeSession(String sessionId) {
        if (!map.containsKey(sessionId)) {
            return;
        }
        ServerSession s = map.get(sessionId);
        map.remove(sessionId);
        System.out.println("用户下线：id=" + s.getUser().getUid() + "    在线总数：" + map.size());
    }

    public boolean hasLogin(User user) {
        for (Map.Entry<String, ServerSession> next : map.entrySet()) {
            User u = next.getValue().getUser();
            if (u.getUid().equals(user.getUid()) && u.getPlatType().equals(user.getPlatType())) {
                return true;
            }
        }
        return false;
    }


}
